<?php

namespace Juheip\IpService;

use Juheip\IpService\exception\InvalidArgementException;
use Juheip\IpService\exception\JuheException;
use Juheip\IpService\factory\PlatformFactory;

class JuheipService
{
    private $platform;

    protected $config;

    public function __construct()
    {
        $this->config = new Config();
    }

    /**
     * 获得当前平台，并生成对应的平台对象
     */
    public function resolve(string $platform, array $config = []): self
    {
        $defaultConfig = $this->config->get($platform, []);

        $finalConfig = array_merge($defaultConfig, $config);

        $this->platform = PlatformFactory::make($platform, $finalConfig);

        return $this;
    }

    public function __call($name, $arguments)
    {
        try {

            return $this->platform->{$name}(...$arguments);
        } catch (\Throwable $e) {
            if ($e instanceof \ArgumentCountError) {
                throw new InvalidArgementException('参数数量异常', 400);
            } else {
                throw new JuheException($e->getMessage(), 400);
            }
        }
    }
}